<template>
    <h3>题目管理</h3>
    <!-- 表单（收集信息）-->
    <div class="topic-form">
        <div class="form">
            <div class="opt">
                <span class="label">考试分类:</span>
                <el-select @change="chooseCategoryFn" v-model="form.id" placeholder="选择分类" style="width: 640px" size="large">
                    <el-option  v-for="item in categories" :key="item.xid" :label="item.text" :value="item.id" />
                </el-select>
            </div>
            <div class="opt">
                <span class="label">试卷名称:</span>
                <el-select @change="chooseExamFn" v-model="form.eid" placeholder="选择试卷" style="width: 640px" size="large">
                    <el-option 
                    v-for="item in result" 
                    :key="item.yid"  
                    :label="item.name" :value="item.eid" />
                </el-select>
            </div>
            <div class="opt">
                <span class="label">题目:</span>
                <el-input v-model="form.question" style="width: 640px" placeholder="请输入题目" size="large" />
            </div>
            <div class="opt">
                <span class="label top">选项:</span>
                <!-- 处理题目的选项A B C D、 -->
                <ul>
                    <li v-for="(item, i) in arr">
                        <input @input="save" class="op" v-model="item.op" type="text" placeholder="" maxlength="1">
                        <input @input="save" class="ov" v-model="item.ov" type="text" placeholder="请输入选项">
                        <el-icon size="large" @click="remove(i)">
                            <Remove />
                        </el-icon>
                    </li>
                    <li>
                        <button class="btn" @click="add">新增选项</button>
                        <!-- <button class="btn btn2" @click="save">保存</button> -->
                    </li>
                </ul>
            </div>


            <div class="opt">
                <span class="label">答案:</span>
                <el-input v-model="form.answer" style="width: 640px" placeholder="请输入答案" size="large" />
            </div>
            <div class="opt">
                <span class="label">分值:</span>
                <el-input v-model="form.score" style="width: 640px" placeholder="分值" size="large" />
            </div>

            <div class="opt">
                <span class="label">数量信息:</span>
                【
                    <span> {{ examInfo.num }}</span> / 
                    <span> {{ count }}</span>
                】
            </div>


            <div class="opt">
                <el-button @click="submitTopicFn" type="primary" size="large">提交题目</el-button>
                <el-button @click="resetTopicFn" type="warning" plain size="large">重置</el-button>
            </div>
        </div>
    </div>
    <!-- 表格（列表） -->
    <div class="topic-list">

    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { categoryList, examList } from '../../api/request'
import api from '../../api/http'
import { ElMessage } from 'element-plus'

interface Item {
    id?: string
    eid: string
    name: string
    question: string
    answer: string
    score: number | string
    option?: string
}
// 针对引用类型的数据做响应式 (对象这个结构)
let form = reactive<Item>({
    eid: "",
    name: "",
    question: "",
    answer: "",
    score: 0,
    id: "",
    option: ""
})

// 记录分类列表
let categories = ref<any>([])
// 试卷列表
let exams = ref<any>([])
// 筛选后的试卷列表
let result = ref<any>([])
// 定义对象记录试卷信息
let examInfo = ref<any>({
    num: 0
})
// 记录这套试卷已经有多少题目数量了
let count = ref<number>(0)

// 对“作答选项”处理
let arr = ref<any>([
    {
        op: "A",
        ov: "",
    },
    {
        op: "B",
        ov: "",
    }
])
let n = arr.value.length - 1;//当前索引值
const add = () => {
    n++;
    if (n < 4) {
        arr.value.push({
            op: "",
            ov: ""
        })
    }
    n = n == 4 ? 4 : n;
}
const remove = (index: number) => {
    n--;
    if (n >= 0) {
        n = 0
    }
    arr.value.splice(index, 1);
}
const save = () => {
    // console.log(arr.value);
    let data = arr.value;
    if (data && data.length != 0) {
        let newArr = [];
        for (let i = 0; i < data.length; i++) {
            // 定义空对象
            let obj: any = {};
            obj['key'] = data[i].op;
            obj['value'] = data[i].ov;
            // 添加数据
            newArr.push(obj);
        }
        // console.log(newArr);
        let str = newArr && JSON.stringify(newArr);
        // console.log(str);
        form.option = str;
    }
}
// ES6 新增数组API   forEach  map  filter  some every 。。。
// 选择分类
const chooseCategoryFn = (value: string)=> {
    // console.log("id:",value);
    // 整合数据
    let arr5 =  exams.value.filter((item: any)=> {
        // 把符合条件的数据保留
        return item.id == value
    })
    result.value = arr5;

    // 在选择分类前，先重置
    form.eid = "";
}
// 选择试卷
const chooseExamFn = async (value: string)=>{
    // console.log("eid:",value);
    // eid
    let arr6 = result.value.filter((item: any)=>{
        return item.eid == value
    })
    if(arr6.length == 1) {
        // 选择哪一套卷子
        examInfo.value = arr6[0]
        // console.log(arr6[0])
        // 题目分值
        form.score = arr6[0].score;
        // 记录试卷名称
        form.name = arr6[0].name;
    }
    // 获取这套试卷已经有多少个题目了
    if(value) {
        // 查询多少题目数量
       await  api.topicNum({eid: value})
       .then(
        content=> {
            // console.log(content)
            let {code, result} = content;
            if(code == 200){
                count.value = result[0].total;
            }
        },
        err=> {
            console.log(err);
        }
       )
    }
}

// 重置表单
const resetTopicFn = async () => {
    // 重置表单
    form.eid = ""
    form.name = ""
    form.question = ""
    form.answer = ""
    form.score = 0
    form.option = ""
    form.id = ""

    // 重置选项
    arr.value = [
        {
            op: "A",
            ov: "",
        },
        {
            op: "B",
            ov: "",
        }
    ]
}
// 提交表单
const submitTopicFn = async () => {
    // 获取表单信息
    let {eid, name, question, answer, score, option} = form;
    // console.log({eid, name, question, answer, score, option});
    if(eid && name && question && answer && score && option) {
        // 新增题目
        api.topicAdd({eid, name, question, answer, score, option})
        .then(
            content=>{
                // console.log(content);
                let {code , msg } = content;
                if(code == 200) {
                    resetTopicFn();
                    ElMessage.success(msg)
                }
                else {
                    ElMessage.error(msg)
                }
            },
            err=>{
                console.log(err);
            }
        )
    }
    else {
        ElMessage.error("缺少参数，请重新提交")
    }
}
// 获取试卷列表
const examListFn = async () => {
    await examList()
        .then(
            content => {
                // console.log('111',content);
                let { code, msg, result } = content;
                if (code == 200) {
                    // 整合数据（为了添加一个唯一的标记）
                    let arr = result.map((item: any, i: number) => {
                        item.yid = i + 1;
                        return item
                    })
                    exams.value = arr;
                }
                else {
                    ElMessage.error(msg)
                }
            }
        )
}
// 获取分类列表
const getCategoryListFn = async () => {
    await categoryList()
        .then(
            content => {
                // console.log(content)
                let { code, result } = content;
                if (code == 200) {
                    let arr = result.map((item: any)=>{
                        item.xid = Math.random().toString().slice(2)
                        return item;
                    })
                    categories.value = arr;
                }
            }
        )
}
// 初始化
examListFn()
getCategoryListFn()

</script>


<style lang="scss">
.topic-form {
    .opt {
        margin-top: 15px;
        width: 100%;
        display: flex;
        align-items: center;

        .label {
            display: inline-block;
            width: 90px;
            text-align: right;
            padding: 0 10px;

            &.top {
                align-self: flex-start;
            }
        }

        ul {
            li {
                margin-bottom: 10px;

                .op {
                    width: 40px;
                    height: 40px;
                    text-align: center;
                    border: 1px solid #ccc;
                }

                .ov {
                    width: 588px;
                    height: 40px;
                    margin-left: 10px;
                    padding-left: 10px;
                }

                .btn {
                    background: yellowgreen;
                    padding: 8px 15px;
                    color: #fff;
                    cursor: pointer;
                    border-radius: 5px
                }

                .btn2 {
                    margin-left: 10px;
                    background-color: deepskyblue;
                }
            }
        }
    }

    .el-icon {
        font-size: 20px !important;
        margin-left: 5px;
        cursor: pointer;
    }
}
</style>